package com.atguigu.gmall.realtime.app.func;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.ververica.cdc.debezium.DebeziumDeserializationSchema;
import io.debezium.data.Envelope;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.util.Collector;
import org.apache.kafka.connect.data.Field;
import org.apache.kafka.connect.data.Struct;
import org.apache.kafka.connect.source.SourceRecord;

import java.util.List;

public class MyDeserializationSchemaFunction implements DebeziumDeserializationSchema<String> {
    @Override
    public void deserialize(SourceRecord sourceRecord, Collector<String> collector) throws Exception {
        // 获取valueStruct
        Struct valueStruct = (Struct)sourceRecord.value();
        Struct sourceStruct = valueStruct.getStruct("source");
        //获取数据库名称
        String dbName = sourceStruct.getString("db");
        // 获取表名称
        String tableName = sourceStruct.getString("table");
        // 获取操作类型
        Envelope.Operation operation = Envelope.operationFor(sourceRecord);
        String type = operation.toString();
        if ("create".equals(type)){
            type = "insert";
        }
        // 获取afterStruct中所有的属性,并封装为dataJson
        JSONObject datajson = new JSONObject();
//        获取afterStruct
        Struct after = valueStruct.getStruct("after");
        if (after != null){
            List<Field> fieldList = after.schema().fields();
            for (Field field : fieldList) {
                datajson.put(field.name(),after.get(field));
            }
        }
        // TODO: 将库名 表名及操作类型和具体数据封装为一个大的json
        JSONObject resJsonObj = new JSONObject();
        resJsonObj.put("database",dbName);
        resJsonObj.put("table",tableName);
        resJsonObj.put("type",type);
        resJsonObj.put("data",datajson);

        collector.collect(resJsonObj.toString());
    }

    @Override
    public TypeInformation<String> getProducedType() {
        return TypeInformation.of(String.class);
    }
}
